﻿using AutoMapper;
using MediatR;
using ProduceBasicData.Api.Application.Command.WarehouseManage;
using ProduceBasicData.Api.DTO.WarehouseDto;
using ProduceBasicData.Domain.WarehouseManage;
using ProduceBasicData.ErrorCode;
using ProduceBasicData.Infrastructure.Interface;

namespace ProduceBasicData.Api.Application.Handler.WarehouseManage
{
    /// <summary>
    /// 获取仓库信息
    /// </summary>
    public class GetWarehouseHandler : IRequestHandler<GetWarehouseCommand, ApiPaging<WarehouseDto>>
    {
        private readonly IBaseRespository<Warehouse> _warehouseRepository;
        private readonly IMapper _mapper;

        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="warehouseRepository"></param>
        /// <param name="mapper"></param>
        public GetWarehouseHandler(IBaseRespository<Warehouse> warehouseRepository, IMapper mapper)
        {
            _warehouseRepository = warehouseRepository;
            _mapper = mapper;
        }
        /// <summary>
        /// 处理
        /// </summary>
        /// <param name="request"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        public async Task<ApiPaging<WarehouseDto>> Handle(GetWarehouseCommand request, CancellationToken cancellationToken)
        {
            var result = new ApiPaging<WarehouseDto>();

            try
            {
                // 获取基础查询（排除已删除的数据）
                var warehouse = await _warehouseRepository.GetAllAsync();
                var query = warehouse.Where(x => x.Isdel == false);

                // 应用查询条件（如果有）
                if (!string.IsNullOrEmpty(request.Keyword))
                {
                    query = query.Where(x =>
                        (x.Code != null && x.Code.Contains(request.Keyword)) ||
                        (x.Name != null && x.Name.Contains(request.Keyword)) ||
                        (x.Remark != null && x.Remark.Contains(request.Keyword)));
                }

                // 获取总记录数
                result.TotalCount = query.Count();

                // 执行分页查询
                if (result.TotalCount > 0)
                {
                    // 应用分页
                    var pagedData = query.OrderByDescending(x => x.CreateTime)
                        .Skip((request.Index - 1) * request.Size)
                        .Take(request.Size)
                        .ToList();

                    // 映射到DTO
                    result.PageDatas = pagedData.Select(x => new WarehouseDto
                    {
                        Id = x.Id,
                        Code = x.Code,
                        Name = x.Name,
                        Type = x.Type,
                        Status = x.Status,
                        Address = x.Address,
                        ManagerId = x.ManagerId,
                        ManagerName = x.ManagerName,
                        ContactPhone = x.ContactPhone,
                        Area = x.Area,
                        Capacity = x.Capacity,
                        Remark = x.Remark,
                        CreateName = x.CreateName,
                        CreateTime = x.CreateTime,
                        UpdateName = x.UpdateName,
                        UpdateTime = x.UpdateTime,
                        Isdel = x.Isdel
                    }).ToList();
                }
                else
                {
                    result.PageDatas = new List<WarehouseDto>();
                }

                result.Code = ApiEnum.Success;
                result.Msg = "查询成功";
            }
            catch (Exception ex)
            {
                // 记录日志（实际项目中应使用专门的日志组件）
                // logger.LogError(ex, "仓库查询异常");

                result.Code = ApiEnum.Failed;
                result.Msg = $"查询异常: {ex.Message}";
                result.PageDatas = new List<WarehouseDto>();
            }

            return result;
        }
    }
}
